<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simulated OS 10 TV For Production Environment - Discovery</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body, html { background: #111 !important; overflow-x: hidden; }
        .top-bar { position: fixed; top: 0; left: 0; width: 100%; background: #222; z-index: 1000; border-bottom: 1px solid #eee; padding: 10px 0; }
        .top-bar .btn { margin-right: 8px; }
        .top-bar .fw-bold { color: #fff; }
        .sidebar { width: 200px; min-width: 200px; max-width: 200px; flex-shrink: 0; background: #222; height: calc(100vh - 56px); top: 56px; padding-top: 0; border-right: 1px solid #eee; position: fixed; left: 0; z-index: 1050; white-space: nowrap; }
        .sidebar .nav-link { color: #fff; font-size: 1.1em; margin-bottom: 8px; border-radius: 8px; transition: background 0.2s, color 0.2s; display: inline-block; float: none; }
        .sidebar .nav-link.active { background: #444; color: #4ea3ff; font-weight: bold; }
        .sidebar .nav-link:hover:not(.active) { background: #333; color: #4ea3ff; }
        .main-content { margin-left: 200px; width: calc(100vw - 200px); padding: 32px 0 0 32px; overflow-x: hidden; background: #111; min-height: calc(100vh - 56px); }
        .discovery-tabs { display: flex; gap: 32px; margin-bottom: 18px; margin-left: 8px; }
        .discovery-tab { color: #ccc; font-size: 1.1em; cursor: pointer; padding: 4px 12px; border-radius: 8px; transition: background 0.2s, color 0.2s; }
        .discovery-tab.active { color: #fff; background: #222; font-weight: bold; }
        .discovery-group { margin-bottom: 36px; }
        .discovery-group-title { color: #fff; font-size: 1.1em; margin-bottom: 12px; margin-left: 8px; }
        .discovery-movie-row { display: flex; gap: 18px; overflow-x: auto; padding-bottom: 8px; scrollbar-width: thin; scrollbar-color: #444 #222; }
        .discovery-movie-row::-webkit-scrollbar { height: 8px; background: #222; border-radius: 6px; }
        .discovery-movie-row::-webkit-scrollbar-thumb { background: #444; border-radius: 6px; }
        .discovery-movie-row::-webkit-scrollbar-thumb:hover { background: #666; }
        .discovery-movie-card { background: #222; border-radius: 14px; box-shadow: 0 2px 12px #0006; cursor: pointer; transition: transform 0.2s, box-shadow 0.2s; position: relative; display: flex; flex-direction: column; }
        .discovery-movie-card-horizontal { width: 400px; min-width: 400px; }
        .discovery-movie-card-horizontal img { width: 100%; height: 225px; object-fit: cover; border-radius: 14px 14px 0 0; }
        .discovery-movie-card-vertical { width: 300px; min-width: 300px; }
        .discovery-movie-card-vertical img { width: 100%; height: 400px; object-fit: cover; border-radius: 14px 14px 0 0; }
        .discovery-movie-title { color: #fff; font-size: 1em; padding: 8px 12px 0 12px; text-align: left; white-space: normal; word-break: break-all; }
        .discovery-movie-card:hover, .discovery-movie-card:focus { transform: scale(1.06); box-shadow: 0 4px 24px #00f4; outline: 2px solid #fff3; }
        #tokenDisplay.copied { position: relative; color: #fff !important; background: #28a745 !important; border-color: #28a745 !important; }
        #tokenDisplay.copied #tokenText { opacity: 0.3; }
        #tokenDisplay.copied::after { 
            content: "\2714 Copied!"; 
            position: absolute; 
            top: 0; left: 0; right: 0; bottom: 0; 
            display: flex; align-items: center; justify-content: center; 
            color: #fff; font-size: 1.1em; background: transparent; z-index: 2; 
        }
        .modal-custom-width .modal-dialog {
            max-width: 1020px;
        }
        .modal-custom-width .modal-content {
            background: #f8f9fa;
        }
    </style>
</head>
<body>
    <!-- 顶部栏 -->
    <div class="top-bar d-flex align-items-center px-4 justify-content-between">
        <span class="fw-bold" style="font-size:1.1em;">Simulated OS 10 TV For Production Environment</span>
        <div class="d-flex align-items-center">
            <button class="btn btn-success btn-sm me-2" id="tokenDisplay">
                <span id="tokenText">TOKEN_PLACEHOLDER</span>
            </button>
            <button class="btn btn-outline-primary btn-sm me-2" id="deviceInfoBtn">Device Info</button>
            <button class="btn btn-outline-warning btn-sm" id="configBtn">Configuration</button>
        </div>
    </div>
    
    <!-- 设备信息弹窗 -->
    <div class="modal fade modal-custom-width" id="deviceInfoModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Device Information</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="deviceInfoContent"></div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 配置弹窗 -->
    <div class="modal fade" id="configModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Device Configuration</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="configForm">
                        <div id="configFormFields" class="row g-3"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-outline-danger" id="configResetBtn">Reset</button>
                    <button type="button" class="btn btn-primary" id="configSaveBtn">Save & Reload</button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="d-flex" style="margin-top:56px;">
        <!-- 侧边栏 -->
        <nav class="sidebar d-flex flex-column p-3">
            <a class="nav-link" href="OS10-home-your-top-choices.html" data-menu="your-top-choice">Your Top Choice</a>
            <a class="nav-link" href="OS10-home.html" data-menu="home">Home</a>
            <a class="nav-link" href="OS10-home-search.html" data-menu="home-search">Home Search</a>
            <a class="nav-link" href="OS10-discovery.html" data-menu="discovery">Discovery</a>
            <a class="nav-link" href="OS10-discovery-search.html" data-menu="discovery-search">Discovery Search</a>
        </nav>
        <!-- 主内容区：Discovery -->
        <div class="main-content flex-grow-1">
            <div id="discoverySection">
                <div class="column-list mb-4">
                    <div class="list-group" id="discoveryList">
                        <!-- 栏目列表填充 -->
                    </div>
                </div>
                <div class="movie-list" id="discoveryMovieList">
                    <!-- 影片列表填充 -->
                </div>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // ========== 顶部按钮和全局变量 ==========
    let GLOBAL_PARAMS = JSON.parse(localStorage.getItem('GLOBAL_PARAMS')) || {
        productId: 'wtv10',
        brandId: '7',
        deviceSetId: '10bfa24f235519482a8b9b1c2ad7a3aef6',
        deviceType: 'WHALEOS_ZEASN_962D4_4K_MTP_P4',
        countryCode: 'DE',
        langCode: 'en',
        mac: '18:84:c1:f4:2c:60',
        functionType: 'TvLauncher',
        ifGetTvDetail: '1',
        iconResolution: '320*180',
        terminalType: 'TV',
        sn: '',
        appVersion: '20000043',
        androidVersion: '13',
        osType: 'WhaleOSA',
        clientIp: '217.111.87.254'
    };
    let globalToken = localStorage.getItem('globalToken') || '';
    let lockedClientIp = GLOBAL_PARAMS.clientIp;
    // 真实接口生成token
    async function fetchToken(force = false) {
        if (!force && globalToken) {
            $('#tokenText').text(globalToken);
            return;
        }
        const params = new URLSearchParams({ ...GLOBAL_PARAMS });
        try {
            const response = await $.ajax({
                url: 'https://saas.zeasn.tv/auth-api/api/v1/auth/deviceSign',
                method: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                data: params.toString(),
                processData: false
            });
            if (response.errorCode !== "0") throw new Error('Failed to get token');
            globalToken = response.data.token;
            $('#tokenText').text(globalToken);
            localStorage.setItem('globalToken', globalToken);
        } catch (e) {
            $('#tokenText').text('Failed to generate');
            globalToken = '';
            localStorage.removeItem('globalToken');
        }
    }
    // 页面初始化自动生成token，按钮背景色为白色
    $(async function() {
        $('#tokenDisplay').removeClass('btn-success').addClass('btn-outline-success');
        if (!globalToken) {
            await fetchToken();
        } else {
            $('#tokenText').text(globalToken);
        }
        // 获取栏目数据
        if (globalToken) {
            try {
                const res = await $.ajax({
                    url: `https://saas.zeasn.tv/sp/api/device/v1/column?token=${globalToken}`,
                    method: 'GET'
                });
                if (res && res.errorCode === "1000") {
                    $('#discoverySection').html(`
                        <div class='text-danger' style='color:#ff6666;padding:32px 0;'>
                            Token expired (errorCode: 1000)<br>
                            <button id='refreshTokenBtn' class='btn btn-danger btn-sm mt-3'>Regenerate Token</button>
                        </div>
                    `);
                    $('#refreshTokenBtn').off('click').on('click', async function() {
                        $('#refreshTokenBtn').prop('disabled', true).text('生成中...');
                        await fetchToken(true);
                        location.reload();
                    });
                    return;
                }
                if (res && res.data) {
                    window.columnData = res.data;
                } else {
                    window.columnData = [];
                }
            } catch (e) {
                window.columnData = [];
            }
        }
        renderDiscoveryGroups();
    });
    // 设备信息渲染
    function renderDeviceInfo(data) {
        if (!data) {
            $('#deviceInfoContent').html('<div class="text-center py-4">No device data available</div>');
            return;
        }
        let rows = '';
        // 主体字段
        const mainFields = [
            ['Product ID', data.productId],
            ['App Version', data.appVersion],
            ['Android Version', data.androidVersion],
            ['Brand ID', data.brandId],
            ['Country Code', data.countryCode],
            ['DeviceSet ID', data.deviceSetId],
            ['Device Type', data.deviceType],
            ['MAC', data.mac],
            ['Language', data.langCode],
            ['IP', data.ip],
            ['OS Type', data.osType],
            ['Function Type', data.functionType],
            ['Token', data.token],
        ];
        mainFields.forEach(([k, v]) => {
            rows += `<tr><td>${k}:</td><td>${v ?? ''}</td></tr>`;
        });
        // tvDetailParam 展开
        if (data.tvDetailParam && typeof data.tvDetailParam === 'object') {
            rows += `<tr><td colspan='2'><b>tvDetailParam</b></td></tr>`;
            Object.entries(data.tvDetailParam).forEach(([k, v]) => {
                rows += `<tr><td style='padding-left:2em;'>${k}:</td><td>${v ?? ''}</td></tr>`;
            });
        }
        $('#deviceInfoContent').html(`<table class="device-info-table"><tbody>${rows}</tbody></table>`);
    }
    // Device Info按钮弹窗
    $('#deviceInfoBtn').off('click').on('click', async function() {
        if (!globalToken) {
            alert('请先生成token');
            return;
        }
        try {
            const res = await $.ajax({
                url: 'https://saas.zeasn.tv/sp/api/device/v1/column/token?token=' + encodeURIComponent(globalToken),
                method: 'GET'
            });
            if (res && res.errorCode === "1000") {
                renderDeviceInfo(null);
                $('#deviceInfoContent').html(`
                    <div class="text-danger text-center py-4">
                        Token expired (errorCode: 1000)<br>
                        <button id="refreshTokenBtn2" class="btn btn-danger btn-sm mt-3">Regenerate Token</button>
                    </div>
                `);
                $('#refreshTokenBtn2').off('click').on('click', async function() {
                    $('#refreshTokenBtn2').prop('disabled', true).text('生成中...');
                    await fetchToken(true);
                    location.reload();
                });
            } else if (res && res.data) {
                renderDeviceInfo(res.data);
            } else {
                renderDeviceInfo(null);
            }
        } catch (e) {
            renderDeviceInfo(null);
            alert('获取设备信息失败');
        }
        const modal = new bootstrap.Modal(document.getElementById('deviceInfoModal'));
        modal.show();
    });
    // 配置弹窗逻辑
    const CONFIG_KEYS = Object.keys(GLOBAL_PARAMS);
    $('#configBtn').click(function() {
        const $fields = $('#configFormFields').empty();
        CONFIG_KEYS.forEach(key => {
            let value = GLOBAL_PARAMS[key];
            $fields.append(`
                <div class="col-12 col-md-6">
                    <label class="form-label fw-bold">${key}</label>
                    <input type="text" class="form-control" name="${key}" value="${value ?? ''}">
                </div>
            `);
        });
        const modal = new bootstrap.Modal(document.getElementById('configModal'));
        modal.show();
    });
    // 配置弹窗保存并生成新token（真实接口）
    $('#configSaveBtn').off('click').on('click', async function() {
        const formArr = $('#configForm').serializeArray();
        formArr.forEach(({name, value}) => {
            GLOBAL_PARAMS[name] = value;
        });
        localStorage.setItem('GLOBAL_PARAMS', JSON.stringify(GLOBAL_PARAMS));
        $('#tokenText').text('Generating...');
        await fetchToken(true); // 强制刷新token
        // 关闭弹窗
        const modal = bootstrap.Modal.getInstance(document.getElementById('configModal'));
        if(modal) modal.hide();
        // 保存后自动刷新页面，确保配置生效
        setTimeout(()=>{ location.reload(); }, 300);
    });
    $('#configResetBtn').click(function() {
        const initial = {
            productId: 'wtv10',
            brandId: '7',
            deviceSetId: '10bfa24f235519482a8b9b1c2ad7a3aef6',
            deviceType: 'WHALEOS_ZEASN_962D4_4K_MTP_P4',
            countryCode: 'DE',
            langCode: 'en',
            mac: '18:84:c1:f4:2c:60',
            functionType: 'TvLauncher',
            ifGetTvDetail: '1',
            iconResolution: '320*180',
            terminalType: 'TV',
            sn: '',
            appVersion: '20000043',
            androidVersion: '13',
            osType: 'WhaleOSA',
            clientIp: '217.111.87.254'
        };
        Object.assign(GLOBAL_PARAMS, initial);
        $('#configForm input').each(function() {
            const key = $(this).attr('name');
            if (key in initial) $(this).val(initial[key]);
        });
        localStorage.removeItem('GLOBAL_PARAMS');
    });
    // Discovery分组渲染
    async function renderDiscoveryGroups() {
        const $container = $('#discoverySection').empty();
        if (!window.columnData) return;
        // 只筛选tag以Discovery-开头的栏目
        const tabCols = window.columnData.filter(g => typeof g.tag === 'string' && g.tag.startsWith('Discovery-'));
        if (!tabCols.length) {
            $container.append('<div class="text-muted" style="padding:48px 0 0 24px;">暂无Discovery相关栏目（tag以Discovery-开头）</div>');
            return;
        }
        const tabNames = tabCols.map(g => g.name);
        const $tabs = $('<div class="discovery-tabs"></div>');
        tabNames.forEach((name, idx) => {
            const $tab = $(`<div class="discovery-tab">${name}</div>`);
            if (idx === 0) $tab.addClass('active');
            $tab.click(function() {
                $tabs.find('.discovery-tab').removeClass('active');
                $tab.addClass('active');
                renderDiscoveryTab(idx);
            });
            $tabs.append($tab);
        });
        $container.append($tabs);
        const $groups = $('<div class="discovery-groups"></div>');
        $container.append($groups);
        renderDiscoveryTab(0);
        async function renderDiscoveryTab(tabIdx) {
            $groups.empty();
            const tabCol = tabCols[tabIdx];
            if (!tabCol || !Array.isArray(tabCol.children)) return;
            for (const group of tabCol.children) {
                const $group = $('<div class="discovery-group"></div>');
                $group.append(`<div class="discovery-group-title">${group.name} <span style='color:#aaa;font-size:0.95em;'>#${group.id}</span></div>`);
                const $row = $('<div class="discovery-movie-row"></div>');
                $row.append(`<div class='text-muted' style='color:#aaa;padding:32px 0;'>Loading...</div>`);
                $group.append($row);
                $groups.append($group);
                // 异步加载影片
                try {
                    const res = await $.ajax({
                        url: `https://saas.zeasn.tv/sp/api/device/v1/column/content?token=${globalToken}&columnIds=${group.id}`,
                        method: 'GET'
                    });
                    if (res && res.errorCode === "1000") {
                        $row.html(`
                            <div class='text-danger' style='color:#ff6666;padding:32px 0;'>
                                Token expired (errorCode: 1000)<br>
                                <button class='btn btn-danger btn-sm mt-3 refreshTokenBtnRow'>Regenerate Token</button>
                            </div>
                        `);
                        $row.find('.refreshTokenBtnRow').off('click').on('click', async function() {
                            $(this).prop('disabled', true).text('生成中...');
                            await fetchToken(true);
                            location.reload();
                        });
                        continue;
                    }
                    $row.empty();
                    if (res && res.data && res.data[0] && res.data[0].content && Array.isArray(res.data[0].content.dataList) && res.data[0].content.dataList.length) {
                        for (const item of res.data[0].content.dataList) {
                            const img = item.icon || item.poster || '';
                            const title = item.name || '';
                            // categories 展示
                            let categoriesStr = '';
                            if (item.moreInfo && Array.isArray(item.moreInfo.categories) && item.moreInfo.categories.length > 0) {
                                categoriesStr = `<div style='color:#ffb84d;font-size:0.97em;padding:0 12px 2px 12px;'>${item.moreInfo.categories.map(c => c.name).join(' / ')}</div>`;
                            }
                            // videoScores 展示
                            let videoScoresStr = '';
                            if (item.moreInfo && Array.isArray(item.moreInfo.videoScores) && item.moreInfo.videoScores.length > 0) {
                                videoScoresStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${item.moreInfo.videoScores.map(vs => `${vs.type||''}: ${vs.value||''}`).join(' / ')}</div>`;
                            }
                            // value 展示
                            let valueStr = '';
                            let objectType = '';
                            let valueObj = null;
                            if (item.value) {
                                valueStr = `<div style='color:#bbb;font-size:0.92em;word-break:break-all;padding:0 12px 2px 12px;'>${item.value}</div>`;
                                try {
                                    valueObj = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                                    objectType = valueObj.objectType || '';
                                } catch (e) {
                                    objectType = '';
                                }
                            }
                            // deeplinkDetailList 展示
                            let deeplinkHtml = '';
                            if (Array.isArray(item.deeplinkDetailList) && item.deeplinkDetailList.length) {
                                deeplinkHtml = `<div style='display:flex;gap:10px;flex-wrap:wrap;padding:0 12px 8px 12px;'>` +
                                    item.deeplinkDetailList.map(link =>
                                        `<div style='display:flex;align-items:center;gap:4px;background:#181818;padding:2px 8px 2px 2px;border-radius:6px;'>`+
                                        (link.sourceIcon ? `<img src='${link.sourceIcon}' style='width:22px;height:22px;border-radius:4px;'>` : '')+
                                        `<span style='color:#fff;font-size:0.97em;'>${link.sourceName||''}</span>`+
                                        `<span style='color:#aaa;font-size:0.85em;'>#${link.sourceId||''}</span>`+
                                        `</div>`
                                    ).join('') + `</div>`;
                            }
                            // releaseTime 展示（格式化）
                            let releaseTimeStr = '';
                            if (item.releaseTime) {
                                const d = new Date(Number(item.releaseTime));
                                if (!isNaN(d.getTime())) {
                                    const y = d.getFullYear();
                                    const m = (d.getMonth()+1).toString().padStart(2,'0');
                                    const day = d.getDate().toString().padStart(2,'0');
                                    releaseTimeStr = `<div style='color:#6cf;font-size:0.92em;padding:0 12px 2px 12px;'>${y}-${m}-${day}</div>`;
                                }
                            }
                            // seasonNumber / episodeCount 展示（仅SEASON类型）
                            let seasonNumber = '';
                            let episodeCount = '';
                            if (item.seasonNumber !== undefined) {
                                seasonNumber = item.seasonNumber;
                            } else if (item.moreInfo && item.moreInfo.seasonNumber !== undefined) {
                                seasonNumber = item.moreInfo.seasonNumber;
                            } else if (item.value) {
                                try {
                                    const v = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                                    if (v.seasonNumber !== undefined) seasonNumber = v.seasonNumber;
                                } catch(e){}
                            }
                            if (item.episodeCount !== undefined) {
                                episodeCount = item.episodeCount;
                            } else if (item.moreInfo && item.moreInfo.episodeCount !== undefined) {
                                episodeCount = item.moreInfo.episodeCount;
                            } else if (item.value) {
                                try {
                                    const v = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                                    if (v.episodeCount !== undefined) episodeCount = v.episodeCount;
                                } catch(e){}
                            }
                            let isSeasonType = (item.objectType === 'SEASON' || (valueObj && valueObj.objectType === 'SEASON'));
                            let seasonInfoStr = '';
                            if (isSeasonType && (seasonNumber || episodeCount)) {
                                let arr = [];
                                if (seasonNumber) arr.push('S' + seasonNumber);
                                if (episodeCount) arr.push(episodeCount + ' episodes');
                                seasonInfoStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${arr.join(' / ')}</div>`;
                            }
                            // duration 展示（仅MOVIE/VIDEO/PROGRAM类型）
                            let duration = '';
                            if (item.duration !== undefined) {
                                duration = item.duration;
                            } else if (item.moreInfo && item.moreInfo.duration !== undefined) {
                                duration = item.moreInfo.duration;
                            } else if (item.value) {
                                try {
                                    const v = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                                    if (v.duration !== undefined) duration = v.duration;
                                } catch(e){}
                            }
                            function formatDuration(d) {
                                d = Number(d);
                                if (isNaN(d) || d <= 0) return '';
                                const h = Math.floor(d / 3600);
                                const m = Math.floor((d % 3600) / 60);
                                const s = d % 60;
                                let arr = [];
                                if (h > 0) arr.push(h + 'h');
                                if (m > 0) arr.push(m + 'm');
                                if (s > 0 || arr.length === 0) arr.push(s + 's');
                                return arr.join(' ');
                            }
                            let isMovieType = (
                                item.objectType === 'MOVIE' || item.objectType === 'VIDEO' || item.objectType === 'PROGRAM' ||
                                (valueObj && (valueObj.objectType === 'MOVIE' || valueObj.objectType === 'VIDEO' || valueObj.objectType === 'PROGRAM'))
                            );
                            let durationStr = '';
                            if (isMovieType && duration) {
                                durationStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${formatDuration(duration)}</div>`;
                            }
                            // 判断竖卡片还是横卡片
                            let cardClass = 'discovery-movie-card-horizontal';
                            if (objectType === 'MOVIE' || objectType === 'SEASON') {
                                cardClass = 'discovery-movie-card-vertical';
                            }
                            const $card = $(`
                                <div class=\"discovery-movie-card ${cardClass}\" tabindex=\"0\">
                                    <img src=\"${img}\" alt=\"${title}\">
                                    <div class=\"discovery-movie-title\">${title}</div>
                                    ${categoriesStr}${videoScoresStr}
                                    <div style='text-align:left;'>${seasonInfoStr}${durationStr}${releaseTimeStr}${valueStr}${deeplinkHtml}</div>
                                </div>
                            `);
                            // 新增：如果是电影，点击跳转到详情页
                            if (objectType === 'MOVIE' && valueObj && valueObj.id) {
                                $card.css('cursor', 'pointer');
                                $card.on('click', function() {
                                    const token = encodeURIComponent(globalToken);
                                    const valueParam = encodeURIComponent(typeof item.value === 'string' ? item.value : JSON.stringify(item.value));
                                    window.open(`movie-detail.html?token=${token}&value=${valueParam}`, '_blank');
                                });
                            }
                            // 新增：如果是季，点击跳转到 season-detail.html
                            if (objectType === 'SEASON' && valueObj && valueObj.id) {
                                $card.css('cursor', 'pointer');
                                $card.on('click', function() {
                                    const token = encodeURIComponent(globalToken);
                                    const valueParam = encodeURIComponent(typeof item.value === 'string' ? item.value : JSON.stringify(item.value));
                                    window.open(`season-detail.html?token=${token}&value=${valueParam}`, '_blank');
                                });
                            }
                            // 新增：如果是视频，点击跳转到 video-detail.html
                            if (objectType === 'VIDEO' && valueObj && valueObj.id) {
                                $card.css('cursor', 'pointer');
                                $card.on('click', function() {
                                    const token = encodeURIComponent(globalToken);
                                    const valueParam = encodeURIComponent(typeof item.value === 'string' ? item.value : JSON.stringify(item.value));
                                    window.open(`video-detail.html?token=${token}&value=${valueParam}`, '_blank');
                                });
                            }
                            $row.append($card);
                        }
                    } else {
                        $row.append(`<div class='text-muted' style='color:#aaa;padding:32px 0;'>暂无内容</div>`);
                    }
                } catch (e) {
                    $row.empty().append(`<div class='text-muted' style='color:#aaa;padding:32px 0;'>加载失败</div>`);
                }
            }
        }
    }
    // 高亮当前菜单
    $(function() {
        const page = location.pathname.split('/').pop();
        $('.sidebar .nav-link').each(function() {
            const href = $(this).attr('href');
            if (href === page) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }
        });
    });
    </script>
    <script>
    $(function() {
        $('#tokenDisplay').off('click').on('click', async function() {
            globalToken = $('#tokenText').text();
            if (!globalToken || globalToken === 'Failed to generate' || globalToken === 'Generating...') {
                alert('当前无可用token');
                return;
            }
            try {
                await navigator.clipboard.writeText(globalToken);
                const $btn = $(this);
                $btn.removeClass('btn-outline-success').addClass('btn-success');
                $btn.addClass('copied');
                setTimeout(() => {
                    $btn.removeClass('btn-success').addClass('btn-outline-success');
                    $btn.removeClass('copied');
                }, 1500);
            } catch (err) {
                alert('Copy failed, please select the token manually');
            }
        });
    });
    </script>
</body>
</html> 